<template>
    <a-input-search v-model:value="state.deptSearchVal" style="margin-bottom: 8px" placeholder="请输入" />
    <a-tree 
        v-if="props.deptData.length > 0" 
        v-model:expandedKeys="state.expandedKeys"
        v-model:selectedKeys="state.selectedKeys" 
        v-model:checkedKeys="state.checkedKeys"
        :auto-expand-parent="state.autoExpandParent" 
        checkable 
        :tree-data="props.deptData"
        :fieldNames="{ title: 'name', key: 'id', children: 'children' }" 
        @expand="onDeptExpand" 
        @check="onDeptCheck"
    >
        <template #title="{ name }">
            <span v-if="name.indexOf(state.deptSearchVal) > -1">
                {{ name.substring(0, name.indexOf(state.deptSearchVal)) }}
                <span style="color: #f50">{{ state.deptSearchVal }}</span>
                {{ name.substring(name.indexOf(state.deptSearchVal) + state.deptSearchVal.length) }}
            </span>
            <span v-else>{{ name }}</span>
        </template>
    </a-tree>
</template>
<script setup lang="ts">
import { apiSysOrgGetDeptUsers } from '@/api/sys/sysOrg';
import type { ResType } from '@/api/types';
import type { TreeProps } from 'ant-design-vue';
import { onBeforeMount, reactive, ref, watch } from 'vue';

const props = withDefaults(defineProps<{
    deptData:[]
}>(),{})

const emits = defineEmits<{
    (e:'change',data:any[]):void
}>()

const state = reactive<any>({
    deptSearchVal: "",
    expandedKeys:[],
    selectedKeys:[],
    checkedKeys:[],
    deptData:[],
    autoExpandParent:true,
    showList:[]
})

const dataList: TreeProps['treeData'] = [];

const generateList = (data: TreeProps['treeData']) => {
    for (let i = 0; i < data.length; i++) {
        const node = data[i];
        const key = node.id;
        dataList.push({ key, title: node.name });
        if (node.children) {
        generateList(node.children);
        }
    }
};
generateList(props.deptData);
const getParentKey = (
    key: string | number,
    tree: TreeProps['treeData'],
    ): string | number | undefined => {
    let parentKey;
    for (let i = 0; i < tree.length; i++) {
        const node = tree[i];
        if (node.children) {
            if (node.children.some(item => item.id === key)) {
                parentKey = node.id;
            } else if (getParentKey(key, node.children)) {
                parentKey = getParentKey(key, node.children);
            }
        }
    }
    return parentKey;
};


const onDeptExpand = (keys:string[])=>{
    state.expandedKeys = keys
    state.autoExpandParent = false
}

const onDeptCheck = (checkedKeys:any[],e:any)=>{
    const checkedNodes:any[] = e.checkedNodes
    // 已选中结果
    state.showList = checkedNodes.map(item=>{
        return {
            id:item.id,
            name:item.name,
            type:"dept"
        }
    })
    emits('change',state.showList)
}

const setCheckedKeys = (keys:any[])=>{
    state.checkedKeys = keys
    state.autoExpandParent = true
}

// 监听部门搜索
watch(
    ()=>state.deptSearchVal,
    (value)=>{
        const expanded = dataList
            .map((item: TreeProps['treeData'][number]) => {
            if (item.title.indexOf(value) > -1) {
                return getParentKey(item.key, props.deptData);
            }
            return null;
            })
            .filter((item, i, self) => item && self.indexOf(item) === i);
        state.expandedKeys = expanded;
        state.deptSearchVal = value;
        state.autoExpandParent = true;
    }   
)

defineExpose({
    setCheckedKeys
})

</script>

<style lang='scss' scoped>
</style>